﻿using System;
using System.Data.SqlClient;
using System.Linq;

namespace StreetPacMan.Server
{
    public interface IRemovedApplesOrders
    {
        int[] GetAllAppleIdsRemovedInTheLastXSeconds(int lastSeconds);
    }
    
    public class RemovedApplesOrders : IRemovedApplesOrders
    {
           private readonly string _ConnectionString;

           public RemovedApplesOrders(IConnectionStringProvider connectionStringProvider)
        {
            _ConnectionString = connectionStringProvider.GetConnectionString();
        }
        
        public int[] GetAllAppleIdsRemovedInTheLastXSeconds(int lastSeconds)
        {
            using (var sqlConnection = new SqlConnection(_ConnectionString))
            using (var pacManDataContext = new PacManDataContext(sqlConnection))
            {
                var lastTimeToReport = DateTime.Now.AddSeconds(lastSeconds*-1);
                return pacManDataContext.Orders
                    .Where(x => x.RemovalTime > lastTimeToReport)
                    .Select(x => x.RemovedAppleId)
                    .ToArray();
            }
        }
    }
}